package 力扣;


/**
 * 输入：l1 = [2,4,3], l2 = [5,6,4]
 * 输出：[7,0,8]
 * 解释：342 + 465 = 807.
 * 示例 2：
 * <p>
 * 输入：l1 = [0], l2 = [0]
 * 输出：[0]
 * 示例 3：
 * <p>
 * 输入：l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
 * 输出：[8,9,9,9,0,0,0,1]
 */
public class _2两数相加 {

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
        // 思路 :注意，进位的情况。
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode retNode = new ListNode(0);
            ListNode currNode = retNode;
            int carry = 0;
            ListNode p = l1, q = l2;
            while (p != null || q != null) {
                int val1 = (p != null) ? p.val : 0;
                int val2 = (q != null) ? q.val : 0;
                int sum = carry + val1 + val2;
                carry = sum / 10;
                currNode.next = new ListNode(sum % 10);
                currNode = currNode.next;
                if (p != null) p = p.next;
                if (q != null) q = q.next;
            }
            if (carry > 0) {
                currNode.next = new ListNode(carry);
            }
            return retNode.next;
        }
        }
}
